/**
 * @Author: LiMeng
 * @Date: 2017/4/18
 */
var GLOBAL = {
    ID: $.getQueryParam("id"),
    CONTRACTOR_ID: '',
    CONTRACTOR_TYPE_ID: '',
    YEARS: [],
    ACTION_URL: '',
    SUBMIT_URL: ROOT_PATH + '/contractor/contractorAudit/submit.shtml'
};
var getSelectedContractor = function (data) {
    data = data[0];
    $('#contractorName').textbox('setValue', data.name);
    $('#contractorId').val(data.id);
    GLOBAL.CONTRACTOR_ID = data.id;
    getSafeCertByContractorId(data.id);
    reloadBusinessDataGrid();
};
var getSelectedContractorStaff = function (data, target) {
    if (target === null || target === '') {
        return;
    }
    data = data[0];

    $('#' + target + 'Name').textbox('setValue', data.name);
    $('#' + target + 'Id').val(data.id);
    getManagerCertByPersonId(data.id, target);
};
var getRecentTwentyYearsComboList = function () {
    var thisYear = new Date().getFullYear();
    for (var i = thisYear + 10; i > thisYear - 10; i--) {
        GLOBAL.YEARS.push({
            value: i,
            text: i
        });
    }
};
var openSelectContractorStaff = function (title, target) {
    title = title || '请选择承包商人员人员';
    target = target || '';
    if (GLOBAL.CONTRACTOR_ID === '') {
        layer.alert('请先选择承包商！');
        return;
    }
    WindowManager.openLayer({
        type: 2,
        title: title,
        area: ['700px', '400px'],
        content: ROOT_PATH + '/contractor/contractorStaff/simpleList.shtml?contractorId=' + GLOBAL.CONTRACTOR_ID,
        callBack: function (data) {
            getSelectedContractorStaff(data, target);
        }
    });
};
var clearTextboxRelatedContractorId = function () {
    $('#responsibleName').textbox('setValue', '');
    $('#responsibleId').val('');
    $('#supervisorName').textbox('setValue', '');
    $('#supervisorId').val('');
    $('#safeDutierName').textbox('setValue', '');
    $('#safeDutierId').val('');
    $('#managerCertCode_responsible').textbox('setValue', '');
    $('#validStartDate_responsible').datebox('setValue', '');
    $('#validEndDate_responsible').datebox('setValue', '');
    $('#managerCertCode_supervisor').textbox('setValue', '');
    $('#validStartDate_supervisor').datebox('setValue', '');
    $('#validEndDate_supervisor').datebox('setValue', '');
    $('#managerCertCode_safeDutier').textbox('setValue', '');
    $('#validStartDate_safeDutier').datebox('setValue', '');
    $('#validEndDate_safeDutier').datebox('setValue', '');
};
var reloadBusinessDataGrid = function () {
    $('#dg1').datagrid('load', {
        contractorId: GLOBAL.CONTRACTOR_ID,
        sort: 'addTime',
        order: 'desc'
    });
};
var getSafeCertByContractorId = function (contractorId) {
    contractorId = contractorId || '';
    if (contractorId === '') {
        return;
    }
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: ROOT_PATH + '/contractor/safeProductCert/selectByContractorId.shtml?contractorId=' + contractorId,
        success: function (result) {
            if (result.success) {
                var data = result.data;
                $('#safeCertCode').textbox('setValue', data.certCode ? data.certCode : '');
                $('#validStartDate').datebox('setValue', data.validStartDate ? data.validStartDate : '');
                $('#validEndDate').datebox('setValue', data.validEndDate ? data.validEndDate : '');
            } else {
                $('#safeCertCode').textbox('setValue', '');
                $('#validStartDate').datebox('setValue', '');
                $('#validEndDate').datebox('setValue', '');
            }
        }
    });
};
var getManagerCertByPersonId = function (personId, target) {
    personId = personId || '';
    if (personId === '') {
        return;
    }
    $.ajax({
        type: 'GET',
        dataType: 'json',
        url: ROOT_PATH + '/contractor/managerCert/selectByPersonId.shtml?personId=' + personId,
        success: function (result) {
            if (result.success) {
                var data = result.data;
                $('#managerCertCode_' + target).textbox('setValue', data.certCode ? data.certCode : '');
                $('#validStartDate_' + target).datebox('setValue', data.validStartDate ? data.validStartDate : '');
                $('#validEndDate_' + target).datebox('setValue', data.validEndDate ? data.validEndDate : '');
            } else {
                $('#managerCertCode_' + target).textbox('setValue', '');
                $('#validStartDate_' + target).datebox('setValue', '');
                $('#validEndDate_' + target).datebox('setValue', '');
            }
        }
    });
};
var toggleFieldDisableState = function (state) {
    $('#contractorName').textbox(state);
    $('#contractorType').combobox(state);
    $('#isEpc').combobox(state);
    $('#isHseSystem').combobox(state);
    $('#year').combobox(state);
    $('#contractorIntellStartDate').datebox(state);
    $('#contractorIntellEndDate').datebox(state);
    $('#responsibleName').textbox(state);
    $('#supervisorName').textbox(state);
    $('#safeDutierName').textbox(state);
    $('.readonly').textbox(state);
};
var setValidStateWhenToggleContractorType = function (text) {
    if (text === '设计') {
        $('.readonly').textbox({
            novalidate: true
        });
        $('#isEpc').combobox('disable');
    } else if (text === '建筑工程') {
        $('.readonly').textbox({
            novalidate: false
        });
        $('#isEpc').combobox('disable');
    } else {
        $('.readonly').textbox({
            novalidate: true
        });
        $('#isEpc').combobox('disable');
    }
    checkValidEndDate();
};
var setElementWithState = function () {
    var state = $.getQueryParam('state');
    var $btn_save = $('#btn_save');
    var $btn_submit = $('#btn_submit');
    switch (state) {
        case 'copy':
            GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/contractorAudit/add.shtml';
            $btn_submit.addClass('hide');
            break;
        case 'edit':
            GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/contractorAudit/edit.shtml';
            break;
        case 'delay':
            GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/contractorAudit/delay.shtml';
            $btn_save.linkbutton({
                iconCls: 'fa fa-calendar-plus-o fa-lg',
                text: '延期'
            });
            $btn_submit.addClass('hide');
            toggleFieldDisableState('disable');
            setValidEndDateAvailable();
            break;
        case 'renew':
            GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/contractorAudit/renew.shtml';
            $btn_save.linkbutton({
                iconCls: 'fa fa-hand-o-right fa-lg',
                text: '续用'
            });
            $btn_submit.addClass('hide');
            $('#contractorName').textbox('disable');
            $('#contractorType').combobox('disable');
            $('#isEpc').combobox('disable');
            $('#isHseSystem').combobox('disable');
            break;
        case 'audit':
            toggleFieldDisableState('disable');
            $btn_submit.addClass('hide');
            GLOBAL.ACTION_URL = ROOT_PATH + '/contractor/contractorAudit/audit.shtml';
            break;
        default:
            toggleFieldDisableState('disable');
            $('.menu-right').addClass('hide');
    }
};
var checkValidEndDate = function () {
    $('.important').each(function () {
        $(this).datebox('textbox').addClass('color-important');
    });
    $('.warning').each(function () {
        $(this).datebox('textbox').addClass('color-warning');
    });
};
var setValidEndDateAvailable = function () {
    $('.important,.warning').each(function () {
        $(this).datebox('enable').datebox('readonly', false);
    });
};
var initPageState = function () {
    GLOBAL.CONTRACTOR_ID = $('#contractorId').val();
    GLOBAL.CONTRACTOR_TYPE_ID = $('#contractorTypeId').val();
    setElementWithState();
    setValidStateWhenToggleContractorType($('#contractorTypeName').val());
    checkValidEndDate();
};
var ajaxSuccessHandler = function (result) {
    result = $.parseJSON(result);
    if (result.success) {
        $.messager.progress('close');	// 如果提交成功则隐藏进度条
        layer.msg(result.message, {time: 1000, icon: 1}, function () {
            var businessId = $.getQueryParam('businessId');
            if (businessId === null) {
                $.getIframeWindow().$('#dg1').datagrid('load');
            }
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        });
    } else {
        $.messager.progress('close');	// 如果提交成功则隐藏进度条
        layer.msg(result.message, {icon: 2});
    }
};
$(function () {
    getRecentTwentyYearsComboList();

    $('#contractorType').combobox({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml?code=' + CONSTANT.DictionaryTypeDefConstants.CONTRACTOR_TYPE,
        valueField: 'id',
        textField: 'text',
        required: true,
        editable: false,
        onChange: function (newVal, oldVal) {
            setValidStateWhenToggleContractorType($(this).combobox('getText'));
        }
    });

    $('#year').combobox({
        data: GLOBAL.YEARS,
        editable: false,
        required: true
    });

    $('#contractorName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                var me = this;
                WindowManager.openLayer({
                    type: 2,
                    title: '选择承包商',
                    area: ['700px', '400px'],
                    content: ROOT_PATH + '/contractor/contractorInfo/simpleList.shtml',
                    callBack: getSelectedContractor
                });
            }
        }],
        editable: false,
        onChange: function (newVal, oldVal) {
            if (newVal !== oldVal) {
                clearTextboxRelatedContractorId();
            }
        }
    });

    $('#responsibleName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectContractorStaff('选择承包商负责人', 'responsible');
            }
        }],
        editable: false
    });

    $('#supervisorName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectContractorStaff('选择承包商主管领导', 'supervisor');
            }
        }],
        editable: false
    });

    $('#safeDutierName').textbox({
        required: true,
        icons: [{
            iconCls: 'icon-search',
            handler: function () {
                openSelectContractorStaff('选择承包商安全负责人', 'safeDutier');
            }
        }],
        editable: false
    });

    initPageState();

    //初始化加载datagrid
    $('#dg1').datagrid({
        method: 'post',
        url: ROOT_PATH + '/contractor/businessQualification/list.shtml',
        queryParams: {
            contractorId: GLOBAL.CONTRACTOR_ID,
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        columns: [[
            {field: 'id', hidden: true},
            {
                field: 'name',
                title: '业务资质名称',
                width: 100,
                sortable: true
            },
            {
                field: 'level',
                title: '业务资质等级',
                width: 100,
                sortable: true,
                formatter: function (value, row, index) {
                    if (typeof value === 'undefined' || value === null || value === '') {
                        return '无';
                    }
                    return $.getChineseInteger(value) + '级';
                }
            },
            {
                field: 'certCode',
                title: '业务资质编号',
                width: 100,
                sortable: true
            },
            {
                field: 'validStartDate',
                title: '开始日期',
                width: 80,
                sortable: true
            },
            {
                field: 'validEndDate',
                title: '结束日期',
                width: 80,
                sortable: true
            },
            {field: 'contractorId', title: '承包商id', hidden: true}
        ]]
    });

    $('#dg2').datagrid({
        method: 'post',
        url: ROOT_PATH + '/contractor/contractorAudit/historyList.shtml',
        queryParams: {
            contractorId: GLOBAL.CONTRACTOR_ID,
            contractorTypeId: GLOBAL.CONTRACTOR_TYPE_ID,
            sort: 'addTime',
            order: 'desc'
        },
        idField: 'id',
        fitColumns: true,
        pagination: true,
        rownumbers: true,
        sortOrder: true,
        striped: true,
        fit: false,
        height: 300,
        singleSelect: true,
        columns: [[
            {field: 'id', hidden: true},
            {
                field: 'contractorTypeName',
                title: '承包商类型',
                width: 100
            },
            {
                field: 'certCode',
                title: '安全许可证编号',
                width: 100,
                formatter: function (value, row, index) {
                    if (row.safeProductCert && row.safeProductCert.certCode) {
                        return row.safeProductCert.certCode;
                    } else {
                        return '';
                    }
                }
            },
            {
                field: 'isQualified',
                title: '是否合格',
                width: 60,
                sortable: true,
                formatter: function (value, row, index) {
                    if (value === 1) {
                        return '是';
                    } else {
                        return '否';
                    }
                }
            },
            {
                field: 'isHseSystem',
                title: '是否建立体系',
                width: 60,
                sortable: true,
                formatter: function (value, row, index) {
                    if (value === 1) {
                        return '是';
                    } else {
                        return '否';
                    }
                }
            },
            {
                field: 'addUserName',
                title: '登记人',
                width: 60
            },
            {
                field: 'addTime',
                title: '登记时间',
                width: 100,
                sortable: true
            },
            {field: 'contractorId', title: '承包商id', hidden: true}
        ]]
    });

    $('#btn_save').on('click', function () {
        $.messager.progress();	// 显示进度条

        $('#form1').form('submit', {
            url: GLOBAL.ACTION_URL,
            onSubmit: function (param) {
                var isValid = $(this).form('validate');
                if (!isValid) {
                    $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
                }
                return isValid;	// 返回false终止表单提交
            },
            success: function (result) {
                ajaxSuccessHandler(result);
            }
        });
    });
    $('#btn_submit').on('click', function () {
        WindowManager.openLayer({
            type: 2,
            title: '选择下一环节处理人',
            area: ['370px', '180px'],
            content: ROOT_PATH + '/workflow/flowManagement/toFlowNextUserSelectPage.shtml',
            callBack: function (data) {//窗口关闭后的回调函数
                //得到选择的人员
                if (typeof data === 'undefined' || data === null) {
                    layer.alert("请选择处理人!");
                    return false;
                }
                $.messager.progress();	// 显示进度条

                $('#form1').form('submit', {
                    url: GLOBAL.SUBMIT_URL,
                    onSubmit: function (param) {
                        param.nextUserId = data;
                        var isValid = $(this).form('validate');
                        if (!isValid) {
                            $.messager.progress('close');	// 如果表单是无效的则隐藏进度条
                        }
                        return isValid;	// 返回false终止表单提交
                    },
                    success: function (result) {
                        ajaxSuccessHandler(result);
                    }
                });
            }
        });
    });
});